package cn.iocoder.yudao.module.member.growth.mq;

import cn.hutool.core.util.DesensitizedUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.iocoder.yudao.framework.common.exception.Assertions;
import cn.iocoder.yudao.module.api.member.growth.enums.MemberGrowthBizTypeEnum;
import cn.iocoder.yudao.module.api.member.vip.message.VipOrderPaidMessage;
import cn.iocoder.yudao.module.api.member.vip.message.VipUserExpiredMessage;
import cn.iocoder.yudao.module.api.member.vip.vo.VipOrderVO;
import cn.iocoder.yudao.module.member.growth.service.core.CoreGrowthRecordService;
import cn.iocoder.yudao.module.member.user.dal.dataobject.MemberUserDO;
import cn.iocoder.yudao.module.member.user.service.MemberUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * <pre>
 * OOoO0OOoO0OOOooo0oOOOO0OOOOO0oooOO0ooOOO0Ooooo0OOOOo0ooooO0OOooo0Ooooo0OOOOO
 *  这里是文件说明
 * OOoO0OOoO0OOOooo0oOOOO0OOOOO0oooOO0ooOOO0Ooooo0OOOOo0ooooO0OOooo0Ooooo0OOOOO
 * </pre>
 *
 * @author 山野羡民（1032694760@qq.com）
 * @since 2025/05/08
 */
@Component
@Slf4j
public class GrowthConsumer {

    @EventListener
    @Async // Spring Event 默认在 Producer 发送的线程，通过 @Async 实现异步
    public void onMessage(VipUserExpiredMessage message) {
        log.info("[member/growth][onMessage][会员过期事件({})]", message);
        Long inviteeUserId = message.getUserId();
        MemberUserDO inviteeUser = SpringUtil.getBean(MemberUserService.class).getUser(inviteeUserId);
        Assertions.notNull(inviteeUser, "受邀人用户信息为空");
        Long inviterUserId = inviteeUser.getPid();
        SpringUtil.getBean(CoreGrowthRecordService.class).createGrowthRecord(inviterUserId, DesensitizedUtil.mobilePhone(inviteeUser.getMobile()), inviteeUser.getCreateTime(), -1, MemberGrowthBizTypeEnum.VIP_EXPIRED, String.valueOf(inviteeUserId));
    }

    @EventListener
    @Async // Spring Event 默认在 Producer 发送的线程，通过 @Async 实现异步
    public void onMessage(VipOrderPaidMessage message) {
        log.info("[member/growth][onMessage][会员缴费完成事件({})]", message);
        VipOrderVO order = message.getOrder();
        Assertions.notNull(order, "会员缴费完成事件携带的订单信息为空");
        if (Boolean.TRUE.equals(order.getRenewal())) {
            log.info("[member/growth][onMessage][会员订单({})支付完成] 会员生效期间续费会员则不发放贡献值", order.getTradeNo());
            return;
        }
        Long inviteeUserId = order.getUserId();
        MemberUserDO inviteeUser = SpringUtil.getBean(MemberUserService.class).getUser(inviteeUserId);
        Assertions.notNull(inviteeUser, "受邀人用户信息为空");
        Long inviterUserId = inviteeUser.getPid();
        SpringUtil.getBean(CoreGrowthRecordService.class).createGrowthRecord(inviterUserId, DesensitizedUtil.mobilePhone(inviteeUser.getMobile()), inviteeUser.getCreateTime(), 1, MemberGrowthBizTypeEnum.VIP_PAID, String.valueOf(inviteeUserId));
    }

}
